﻿using System;
using System.Web;
using EPiServer.Personalization;
using EPiServer.Security;

namespace EPiServer.Research.VirtualRoles
{
    public class ScoreRole : VirtualRoleProviderBase
    {
        public string ScoreName { get; set; }
        public int Min { get; set; }
        public int Max { get; set; }

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            if (!string.IsNullOrEmpty(config["scorename"])) ScoreName = config["scorename"];
            if (!string.IsNullOrEmpty(config["min"]))
            {
                Min = int.Parse(config["min"]);
            }
            else Min = int.MinValue;
            if (!string.IsNullOrEmpty(config["max"]))
            {
                Max = int.Parse(config["max"]);
            }
            else Max = int.MaxValue;

            VirtualRolesInit vri = new VirtualRolesInit();
            vri.Subscribe((page) => HandleScore(page));

        }

        public override bool IsInVirtualRole(System.Security.Principal.IPrincipal principal, object context)
        {
            if (HttpContext.Current == null) return false;
            if (EPiServerProfile.Current == null) return false;
            if (EPiServerProfile.Current[ScoreName] == null) return false;
            int v = (int)EPiServerProfile.Current[ScoreName];
            return (v > Min) && (v < Max);

        }

        private void HandleScore(PageBase page)
        {
            if (page != null && page.CurrentPage != null && page.CurrentPage[ScoreName] != null && page.CurrentPage[ScoreName] is int)
            {
                int score = (int)page.CurrentPage[ScoreName];
                EPiServerProfile.Current.SetPropertyValue(ScoreName, ((int)EPiServerProfile.Current[ScoreName]) + score);
                EPiServerProfile.Current.Save();
            }
        }
    }
}
